package cn.iscorpio.ssm.common;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenkx
 * @date 2018-04-19.
 */
public class CommonService<T, ID extends Serializable> {

    private CommonMapper<T, ID> mapper;

    protected void setMapper(CommonMapper mapper) {
        this.mapper = mapper;
    }

    public PageInfo<T> listAsPage(T t, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> mapper.select(t));
    }

    public T getById(ID id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<T> findByEntity(T t) {
        return mapper.select(t);
    }

    public List<T> findByIds(String ids) {
        return mapper.selectByIds(ids);
    }

    public List<T> findByIds(List<ID> ids) {
        return mapper.selectByIds(String.join(",", ids.stream().map(Object::toString).collect(Collectors.toList())));
    }

    public Long count(T t) {
        return Integer.toUnsignedLong(mapper.selectCount(t));
    }

    public boolean existsWithPrimaryKey(ID id) {
        return mapper.existsWithPrimaryKey(id);
    }

    public void saveAll(List<T> recordList) {
        mapper.insertList(recordList);
    }

    public int save(T t) {
        return this.save(t, true);
    }

    public int save(T t, boolean isSelective) {
        if (isSelective) {
            return mapper.insertSelective(t);
        } else {
            return mapper.insert(t);
        }
    }

    public int update(T t) {
        return this.update(t, true);
    }

    public int update(T t, boolean isSelective) {
        if (isSelective) {
            return mapper.updateByPrimaryKeySelective(t);
        } else {
            return mapper.updateByPrimaryKey(t);
        }
    }

    public void delete(T t) {
        mapper.delete(t);
    }

    public void deleteById(ID id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void deleteByIds(String ids) {
        mapper.deleteByIds(ids);
    }

    public void deleteByIds(List<ID> ids) {
        mapper.deleteByIds(String.join(",", ids.stream().map(Object::toString).collect(Collectors.toList())));
    }

}
